package com.qt.myboot.controller;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.qt.myboot.common.BootConstants;
import com.qt.myboot.common.Result;
import com.qt.myboot.entity.User;
import com.qt.myboot.enums.ResultEnum;
import com.qt.myboot.service.UserService;
import com.qt.myboot.utils.JwtUtil;
import com.qt.myboot.utils.MD5Util;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;


@RestController
@RequestMapping("user")
public class LoginController {

    private UserService userService;

    public LoginController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping("/login")
    public Result login(@RequestBody User user, HttpServletResponse response) {
        User byName = userService.findByName(user);
        if (null == byName) {
            return new Result(ResultEnum.USER_NOT_EXIST, false);
        }
        User vo = userService.findUser(user);
        if (null == vo) {
            return new Result(ResultEnum.LOGIN_FAILED, false);
        }
        //使用权限工具进行用户登录，登录成功后跳到shiro配置的successUrl中
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user.getUserName(), MD5Util.encode(user.getPassword(), BootConstants.SALT));
        // usernamePasswordToken.setRememberMe(false);
        subject.login(usernamePasswordToken);

        String token = JwtUtil.buildJWT(vo.getUserName(), BootConstants.jwtAud, String.valueOf(vo.getId()), BootConstants.SIGNATURE, DateTime.now().toDate(), 3 );
        response.setHeader("Authorization", token);

        return new Result(ResultEnum.LOGIN_SUCEESS, true, token);

    }


}
